package com.nanhu.test.media;

import java.io.File;
import java.io.IOException;

import com.nanhu.test.R;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MediaPlayerTestActivity extends Activity {

	private static final String TAG = "PlayActivity";

	private EditText fileNameText;

	private MediaPlayer mediaPlayer;

	private String fileName;

	private int position;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.media_player_layout);
		fileNameText = (EditText) findViewById(R.id.fileNameEditText);
		fileName = fileNameText.getText().toString();
		fileName = "/Music/蔡琴 - 09.敖包相会(新疆民歌).mp3";
		mediaPlayer = new MediaPlayer();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putString("filename", fileName);
		outState.putInt("position", position);
		super.onSaveInstanceState(outState);
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		this.fileName = savedInstanceState.getString("filename");
		this.position = savedInstanceState.getInt("position");
		super.onRestoreInstanceState(savedInstanceState);
	}
	
	@Override
	protected void onPause() {
		if(mediaPlayer.isPlaying()){
			position = mediaPlayer.getCurrentPosition();
			mediaPlayer.stop();
		}
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		if(position > 0 && fileName != null){
			play(null);
			mediaPlayer.seekTo(position);
			position = 0;
		}
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		mediaPlayer.release();
		super.onDestroy();
	}

	public void play(View view) {
		try {
			File audioFile = new File(Environment.getExternalStorageDirectory(), fileName);
			mediaPlayer.reset();
			mediaPlayer.setDataSource(audioFile.getAbsolutePath());
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void pause(View view) {
		Button bt = (Button) view;
		if (mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
			bt.setText("继续");
		}else{
			mediaPlayer.start();
			bt.setText("暂停");
		}
	}

	public void reset(View view) {
		if (mediaPlayer.isPlaying()) {
			mediaPlayer.seekTo(0);
		} else {
			mediaPlayer.start();
		}
	}

	public void stop(View view) {
		if (mediaPlayer.isPlaying()) {
			mediaPlayer.stop();
		}
	}
}
